﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using WebApiTest.DAL;
using WebApiTest.ModelPlus;
using WebApiTest.Models;
using WebApiTest.Tools;

namespace WebApiTest.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CallBackController : ControllerBase
    {
        private readonly ILogger<CallBackController> _logger;
        public CallBackController(ILogger<CallBackController> logger)
        {
            _logger = logger;
        }

        [HttpPost("deviceDatachanged")]
        public async Task<IActionResult> deviceDataChangedAsync([FromBody] DeviceDataPost value)
        {
            try
            {
                if (value != null&& value.service.data.msgtype!=175)
                {
                    //时间转换
                    var eventTime = Simple.CtStringConvertDateTime2(value.service.eventTime);
                    var NBCallback = new NBCallbackDAL();
                    //记录原始数据
                    var A= NBCallback.MeterRecordSave(value.service.data, value.deviceId, eventTime);
                    //04磁报警攻击
                    if (value.service.data.msgtype == 4)
                    {
                        await NBCallback.InsertWarningMagnetism(value.service.data, value.deviceId, eventTime);
                    }
                    //异步向结算表插数据
                    await NBCallback.InsertSettlementDay(value.service.data, value.deviceId, eventTime);
                    await A; 
                    //return Ok(new { errcode = 0, msg = "device data saved." });
                }
                return Ok(new { errcode = 0, msg = "device data saved." });
                //else
                //{
                //    //_logger.LogError("电信回调数据消息：传入数据为空");
                //    return Ok(new { errcode = 1, msg = "CallBack Error" });
                //}
            }
            catch (Exception e)
            {
                _logger.LogError($"保存错误上传记录：{ JsonConvert.SerializeObject(value)}");
                _logger.LogError("数据消息回调：" + e.Message);
                return Ok(new { errcode = 1, msg = "CallBack Error" });
            }
        }
    }
}
